/*
 * @Overview     : JsBridge
 * @Author       : Zi Jun
 * @Email        : zijun2030@163.com
 * @Date         : 2021-01-20 17:16:41
 * @LastEditTime : 2021-01-20 18:09:55
 * @LastEditors  : Zi Jun
 * @FilePath     : \simple-vue\src\utils\js-bridge\index.ts
 * @Mark         :
 *
 * 用法：
 * import jsBridge from '@/utils/js-bridge'
 *
 * 1、给 APP 端发送数据
 * jsBridge.callHandler(eventName, data, callback(responseData))
 * 参数说明：
 * eventName (string): 必传, 与 APP 端约定的事件名
 * data (object): 非必传, 发送给 APP 端的数据
 * callback (function): 通信完成后，前端的回调，responseData，是APP端返回的数据
 *
 * 2、接收 APP 端的数据
 * jsBridge.registerHandler(eventName, callback(data, responseCallback))
 * 参数说明：
 * eventName (string): 必传，与 APP 端约定的事件名
 * callback (function): data: 是接收到的数据，responseCallback，通信完成后，传给 APP 端的回调
 */

import { getBrowser } from '@/utils/methods/common';

const setupBridge = (callback: any): unknown => {
  if (getBrowser().isAndroid) {
    if (window.WebViewJavaScriptBridge) {
      callback(window.WebViewJavaScriptBridge);
    } else {
      document.addEventListener(
        'webViewJavaScriptBridgeReady',
        function () {
          callback(window.WebViewJavaScriptBridge);
        },
        false,
      );
    }
  }
  if (getBrowser().isIos) {
    if (window.WebViewJavaScriptBridge) {
      return callback(window.WebViewJavaScriptBridge);
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback);
    }
    window.WVJBCallbacks = [callback];
    const WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(() => {
      document.documentElement.removeChild(WVJBIframe);
    }, 0);
  }
};

setupBridge((bridge: { init: (arg0: (message: any, responseCallback: any) => void) => void }) => {
  // 安卓端，接收数据时，需要先进行初始化
  if (getBrowser().isAndroid && !getBrowser().isWeChat && !getBrowser().isWXProgram) {
    bridge.init(function (message: any, responseCallback: () => void) {
      responseCallback();
    });
  }
});

export default {
  // 给APP发送数据
  callHandler(name: string, data: Record<string, unknown>, callback?: any) {
    setupBridge(function (bridge: any) {
      bridge.callHandler(name, data, callback);
    });
  },
  // 接收APP端数据
  registerHandler(name: string, callback?: any) {
    setupBridge(function (bridge: any) {
      bridge.registerHandler(name, function (data: any, responseCallback: any) {
        callback(data, responseCallback);
      });
    });
  },
};
